package org.openstreetmap.gui.jmapviewer;

//License: GPL. Copyright 2008 by Jan Peter Stotz

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JApplet;

import org.openstreetmap.gui.jmapviewer.interfaces.TileLoader;
import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.BingAerialTileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
import org.openstreetmap.gui.jmapviewer.MapMarkerLine;

import java.sql.*;
/**
 *
 * Demonstrates the usage of {@link JMapViewer}
 *
 * @author Jan Peter Stotz
 *
 */
public class Demo extends JApplet implements Runnable {

    private static final long serialVersionUID = 1L;
    
    JMapViewer map = new JMapViewer();
    Thread thread;
    private Connection conn;
	private Statement stmt;
	private String pilote = "org.gjt.mm.mysql.Driver";
	private String url = new String("jdbc:mysql://127.0.0.1/transat_database");
	Trimaran bateau;
	
    public void init() {
        //super("JMapViewer Demo");
        this.setSize(800, 800);
        
        // final JMapViewer map = new JMapViewer(new MemoryTileCache(),4);
        // map.setTileLoader(new OsmFileCacheTileLoader(map));
        // new DefaultMapController(map);
        this.setLayout(new BorderLayout());
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //setExtendedState(JFrame.MAXIMIZED_BOTH);
        JPanel panel = new JPanel();
        JPanel panel_commandes = new JPanel();
        add(panel, BorderLayout.NORTH);
        add(panel_commandes, BorderLayout.SOUTH);
        JButton button = new JButton("Zoomer sur la course");
        JButton tourner_gauche = new JButton("gauche");
        JButton tourner_droite = new JButton("droite");
        final JButton gerer_ancre = new JButton("lever l'ancre");
        JButton reduire_vitesse = new JButton("-");
        JButton augmenter_vitesse = new JButton("+");
        panel_commandes.add(tourner_gauche);
        panel_commandes.add(tourner_droite);
        panel_commandes.add(gerer_ancre);
        panel_commandes.add(reduire_vitesse);
        panel_commandes.add(augmenter_vitesse);
        
        gerer_ancre.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		if(gerer_ancre.getText().equals("Jeter l'ancre")) {
        			bateau.setAllure("arret");
        			gerer_ancre.setText("Lever l'ancre");
        		}
        		else {
        			bateau.setAllure("en marche");
        			gerer_ancre.setText("Jeter l'ancre");
        		}
        	}
        });
        
        reduire_vitesse.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		if(bateau.getVitesse() == 0) {
        			
        		} else {
        			bateau.setVitesse(bateau.getVitesse() - 1);
        		}
        	}
        });
        
        augmenter_vitesse.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		if(bateau.getVitesse() == 20) {
        			
        		} else {
        			bateau.setVitesse(bateau.getVitesse() + 1);
        		}
        	}
        });
        
        tourner_gauche.addActionListener(new ActionListener() {
        	
        	public void actionPerformed(ActionEvent e) {
        		bateau.tourner_gauche();
        	}
        });
        tourner_droite.addActionListener(new ActionListener() {
        	
        	public void actionPerformed(ActionEvent e) {
        		bateau.tourner_droite();
        	}
        });
        
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                map.setDisplayToFitMapMarkers();
            }
        });
        
        JComboBox tileSourceSelector = new JComboBox(new TileSource[] { new OsmTileSource.Mapnik(),
                new OsmTileSource.TilesAtHome(), new OsmTileSource.CycleMap(), new BingAerialTileSource() });
        tileSourceSelector.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                map.setTileSource((TileSource) e.getItem());
            }
        });
        
        JComboBox tileLoaderSelector;
        
        try {
            tileLoaderSelector = new JComboBox(new TileLoader[] { new OsmFileCacheTileLoader(map),
                    new OsmTileLoader(map) });
        } catch (IOException e) {
            tileLoaderSelector = new JComboBox(new TileLoader[] { new OsmTileLoader(map) });
        }
        tileLoaderSelector.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                map.setTileLoader((TileLoader) e.getItem());
            }
        });
        //map.setTileLoader((TileLoader) tileLoaderSelector.getSelectedItem());
        panel.add(new JLabel("Aspect de la carte : "));
        panel.add(tileSourceSelector);
        //panel.add(tileLoaderSelector);
        
        final JCheckBox showTileGrid = new JCheckBox("Afficher la carte des vents");
        showTileGrid.setSelected(map.isTileGridVisible());
        showTileGrid.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                map.setTileGridVisible(showTileGrid.isSelected());
            }
        });
        panel.add(showTileGrid);
        
        panel.add(button);
        add(map, BorderLayout.CENTER);


        // map.setDisplayPositionByLatLon(49.807, 8.6, 11);
        // map.setTileGridVisible(true);
        
        try
		{
			ResultSet lignes;
			ResultSet bateaux;
			Class.forName(pilote);
			conn = (Connection)DriverManager.getConnection(url,"root","");
			stmt = (Statement)conn.createStatement();
			lignes = (ResultSet)stmt.executeQuery("select * from ligne_passage where id_regate = 3");
			
			while(lignes.next())
			{
				map.addMapMarker(new MapMarkerDot(Color.RED, lignes.getDouble(3), lignes.getDouble(5)));
				map.addMapMarker(new MapMarkerDot(Color.RED, lignes.getDouble(4), lignes.getDouble(6)));
				map.addMapLine(new MapMarkerLine(Color.RED, lignes.getDouble(3), lignes.getDouble(5), lignes.getDouble(4), lignes.getDouble(6)));
				javax.swing.JOptionPane.showMessageDialog(null, lignes.getDouble(3) + " " + lignes.getDouble(4));
				javax.swing.JOptionPane.showMessageDialog(null, lignes.getDouble(5) + " " + lignes.getDouble(6));
			}
			
			bateaux = (ResultSet)stmt.executeQuery("select * from navigation where id_regate = 3");
			
			while(bateaux.next())
			{
				bateau = new Trimaran(Color.BLUE, bateaux.getDouble(7), bateaux.getDouble(8));
				javax.swing.JOptionPane.showMessageDialog(null, bateaux.getDouble(7));
				//map.addMapMarker(new MapMarkerDot(Color.BLUE, bateaux.getDouble(7), bateaux.getDouble(8)));
				
			}
			
		}
        catch(Exception e)
        {
        	javax.swing.JOptionPane.showMessageDialog(null, "erreur");
        }
        
    }

    public void start()
	{
		thread = new Thread(this);
		thread.start();
	}
	
	public void stop()
	{
		thread = null;
	}
    
    public void run()
    {
    	//DecimalFormat df = new DecimalFormat("#.##");
    	javax.swing.JOptionPane.showMessageDialog(null, "arg1");
    	for(int i = 0; i < 30000; i++) {
    		this.bateau.avancer();
    	if(bateau.getAllure() == "en marche") {
    		this.bateau.avancer();
    		if(bateau.getAllure().equals("en marche")) {
    			//labels[0].setText("levée");
    		} else {
    			//labels[0].setText("jetée");
    		}
    		//labels[1].setText(Double.toString(marqueur_bateau.getAngle()));
    		//labels[2].setText(Double.toString(marqueur_bateau.getVitesse()));
    		//String coordonnees = Double.toString(round(bateau.getLat(),3)) + " " + Double.toString(round(bateau.getLon(),3));
    		//labels[3].setText(coordonnees);
    	}
    	
    	this.map.addMapMarker(bateau);
    	
    	try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		
		this.map.removeMapMarker(bateau);
		
    	}
    	javax.swing.JOptionPane.showMessageDialog(null, "arg2");
    }
    
    /**
     * @param args
     */
    /*public static void main(String[] args) {
        // java.util.Properties systemProperties = System.getProperties();
        // systemProperties.setProperty("http.proxyHost", "localhost");
        // systemProperties.setProperty("http.proxyPort", "8008");
        new Demo().setVisible(true);
    }*/

}
